﻿using ImageWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using Common;
using DataLibrary;

namespace ImageWeb.Controllers
{
    
    public class LoginController : Controller
    {

        private PublicMethod pm = new PublicMethod();
        private ImageManagerEntities ime = new ImageManagerEntities();

        [AllowAnonymous]
        public ActionResult Index()
        {
            return RedirectToAction("Login", "Login");
        }
        //
        // GET: /Login/
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Login(LoginModel loginModel, string cnt)
        {
            if (!string.IsNullOrEmpty(cnt))
            {
                int fieldCnt = System.Convert.ToInt32(cnt);
                if (fieldCnt > 2)
                {
                    if (Session["ValidateCode"].ToString() != loginModel.valicode)
                    {
                        ModelState.AddModelError("valicode", "验证码错误");
                        return View(loginModel);
                    }
                }
            }
            if (ModelState.IsValid)
            {
                string _passowrd = pm.EncryptString(loginModel.Password);
                var users = ime.Users.Where(u => u.UserNum == loginModel.userNum).Take(1);
                if (users == null)
                {
                    ModelState.AddModelError("UserNum", "用户名不存在");
                }
                else if (users.First().Password == _passowrd)
                {
                    var user = users.First();
                    if (RedisHelper.Get<string>("web" + user.UserID.ToString()) != null)
                    {
                        RedisHelper.DelKey("web" + user.UserID.ToString());
                    }
                    RedisHelper.Set<string>("web" + user.UserID.ToString(), Session.SessionID, DateTime.Now.AddHours(2) - DateTime.Now);
                    if (RedisHelper.Get<string>("EditRange" + user.UserID.ToString()) == null)
                    {
                        RedisHelper.Set<string>("EditRange" + user.UserID.ToString(), "100", DateTime.Now.AddDays(1) - DateTime.Now);
                    }                    
                    Session.Add("UserID", user.UserID);
                    Session.Add("UserNum", user.UserNum);
                    Session.Add("UserName", user.Name);
                    Session.Add("RoleID", user.RoleID);
                    //这里加一个检测权限的函数
                    user.Logined_at = DateTime.Now;                    
                    user.Logined_IP = Request.UserHostAddress;
                    user.Logined_type = 1;
                    ime.SaveChanges();
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("Password", "密码错误");
                }
            }
            return View(loginModel);
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Register(RegisterModel registerModel)
        {
            int code = 0;
            string info = "";
            try
            {
                if (ModelState.IsValid)
                {
                    if (ime.Users.Where(u => u.UserNum == registerModel.UserNum).Count() > 0)
                    {
                        code = 2;
                        info = "该员工编号已存在";
                    }
                    else
                    {
                        if (Session["ValidateCode"].ToString() != registerModel.valicode)
                        {
                            code = 3;
                            info = "验证码错误";
                        }
                        else
                        {
                            Users user = new Users();
                            user.UserNum = registerModel.UserNum;
                            user.Password = pm.EncryptString(registerModel.Password);
                            user.Name = registerModel.Name;
                            user.Email = registerModel.Email;
                            user.Created_at = DateTime.Now;
                            user.Updated_at = DateTime.Now;
                            user.Logined_at = DateTime.Now;
                            user.Logined_type = 0;
                            user.RoleID = 2;
                            user.Logined_IP = Request.UserHostAddress;
                            user.Location = string.IsNullOrEmpty(registerModel.Location) ? "保定" : registerModel.Location;
                            ime.Users.Add(user);
                            ime.SaveChanges();
                            code = 1;
                            info = "注册成功,即将跳转到登录界面...";
                            if (!string.IsNullOrEmpty(registerModel.Email))
                            { Email.SendEmail(registerModel.Email, "注册成功", "欢迎注册，编号为" + registerModel.UserNum + "的员工，您可以在本平台进行相关操作，如需高级授权请联系wtlemon@126.com。发送时间" + DateTime.Now); }
                            System.Threading.Thread.Sleep(2000);

                            return RedirectToAction("Login", "Login");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                code = -1;
                info = ex.Message;
            }
            return Json(new { code = code, info = info });
        }

        [AllowAnonymous]
        public ActionResult ForgetPwd1(string email, string _code)
        {
            int code = 0;
            string info = "";
            if (Session["ValidateCode"].ToString() != _code)
            {
                code = 0;
                info = "验证码错误";
            }
            else
            {
                var user = ime.Users.Where(u => u.Email == email);
                if (user != null && user.Count()>0)
                {
                    Random rd = new Random();
                    Session["F_Validate"] = rd.Next(1000, 9999);
                    Email.SendEmail(email, "找回密码", Session["F_Validate"].ToString());
                    code = 1;
                    info = "识别码已发送到您的邮箱，请在接下来的操作中输入该识别码";
                }
                else
                {
                    code = 0;
                    info = "用户不存在";
                }
            }
            return Json(new { code = code, info = info }, JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        public ActionResult ForgetPwd2(string f_Validate)
        {
            int code = 0;
            string info = "";
            if (f_Validate == Session["F_Validate"].ToString())
            {
                code = 1;
            }
            else
            {
                code = 0;
                info = "识别码错误";
            }
            return Json(new { code = code, info = info }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult ForgetPwd3(string email, string newPwd, string f_Validate)
        {            
            int code = 0;
            string info = "";
            if (f_Validate == Session["F_Validate"].ToString())
            {
                try
                {
                    var user = ime.Users.Where(u => u.Email == email).First();
                    string pwd = pm.EncryptString(newPwd);
                    user.Password = pwd;
                    user.Updated_at = DateTime.Now;
                    ime.SaveChanges();
                    code = 1;
                    info = "密码重置为：" + newPwd;
                }
                catch(Exception ex){
                    code = -1;
                    info = ex.Message;
                }
            }
            else
            {
                code = 2;
                info = "不要偷偷修改js代码哦，修改失败了呢";
            }
            return Json(new { code = code, info = info });
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult CetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
    }
}